﻿// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'

Shader "Unlit/f2"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
		_fresnelBase("fresnelBase", Range(0, 1)) = 1
		_fresnelScale("fresnelScale", Range(0, 1)) = 1
		_fresnelIndensity("fresnelIndensity", Range(0, 5)) = 5
		_fresnelCol("_fresnelCol", Color) = (1,1,1,1)
		_Environment ("Environment", Cube) = "white" // 立方环境贴图
	}

	SubShader
	{
		Tags { "RenderType"="Opaque" }
		LOD 100

		Pass
		{
			tags{"lightmode="="forward"}

			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"
			#include "Lighting.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
				float3 normal : NORMAL;
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				float4 vertex : SV_POSITION;
				float3 L : TEXCOORD1;
				float3 N : TEXCOORD2;
				float3 V : TEXCOORD3;
				float3 R : TEXCOORD4;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;

			float _fresnelBase;

			float _fresnelScale;

			float _fresnelIndensity;

			float4 _fresnelCol;

			samplerCUBE _Environment;


			v2f vert (appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = TRANSFORM_TEX(v.uv, _MainTex);
				o.N = normalize(mul(v.normal, (float3x3)unity_WorldToObject));
				o.L = normalize(WorldSpaceLightDir(v.vertex));
				o.V = normalize(WorldSpaceViewDir(v.vertex));

				// 将顶点转换到世界坐标
                float3 posW = mul(unity_ObjectToWorld,v.vertex).xyz;
                // 世界空间摄像机射向该顶点的向量
                float3 I = normalize(posW -_WorldSpaceCameraPos.xyz);

                o.R = I-2*dot(o.N, I)*o.N;
				return o;
			}

			fixed4 frag (v2f i) : SV_Target
			{
				fixed4 col = tex2D(_MainTex, i.uv);

				float3 N = i.N;
				float3 L = i.L;
				float3 V = i.V;

				float4 reflectiveColor = texCUBE(_Environment,i.R);

				col.rgb *= saturate(dot(N, L)) * _LightColor0.rgb;

				float fresnel = _fresnelBase + _fresnelScale*pow(1 - dot(N, V), _fresnelIndensity);

				col.rgb += lerp(col.rgb, reflectiveColor, fresnel);

				return col;
			}

			ENDCG
		}
	}
}
